/**
 * Created by webhugo on 16-10-18.
 */

const db = require('../../model/index')
const Post = db.models.Post;
const Reply = db.models.Reply;
const User = db.models.User;
const utilx = require('../../lib/utilx');
const auth = require('../../helper/auth');
var responser = require("../../lib/responser");

module.exports = router=> {
    /**
     * 参数 page 第几页  count 数量  order 0是按创建日期，1是按回复数量  search 查询title
     */
    router.get('/forum/index', async function (ctx, next) {
        let query = ctx.query;

        let conditions = {
            where: {}
        };

        let page = parseInt(query.page);
        page = page || 1;
        let count = parseInt(query.count);
        count = count || 10;
        let order = parseInt(query.order);
        order = order || 0;

        //todo: 模糊查询
        if (query.search) {
            conditions.where.title = {
                like: `%${query.search}%`
            };
        }

        // let total = await Post.count(conditions);

        conditions.limit = count;
        conditions.offset = (page - 1) * count;
        if (order == 0) {
            conditions.order = [['createdAt', 'DESC']]
        } else {
            conditions.order = [['replyCount', 'DESC']]
        }
        console.log(conditions);
        try {
            var list = await Post.findAll(conditions);
        } catch (e) {
            responser.catchErr(ctx, e);
            return;
        }
        responser.success(ctx, {
            list: list
        });
    });

    router.get('/forum/all', async function (ctx, next){
        var list = await Post.findAll({
            include: [
                {
                    model: db.models.User,
                    attributes: ['username']
                }
            ]
        });
        responser.success(ctx,{
            list: list
        })
    });

    /**
     * 参数id，贴头的id
     */
    router.get('/forum/getComment', async(ctx, next) => {
        console.log('/forum/getComment');
        var query = ctx.query;
        var id = query.id;

        if (!id) {
            responser.catchErr(ctx, "参数缺失");
            return;
        }
        try {
            var list = await Reply.findAll({
                where: {
                    PostId: id
                },
                include: [
                    {
                        model: db.models.User,
                        attributes: ['avatar', 'username']
                    }
                ]
            })
        } catch (err) {
            responser.catchErr(ctx, "该帖子不存在");
            return;
        }
        responser.success(ctx, {
            list: list
        });
    });

    /**
     * 发帖,text是内容,userId是发帖人的id
     */
    router.post('/forum/addTopic', async(ctx, next) => {
        let body = ctx.request.body

        var text = body.text;
        var title = body.title;
        
        if (null == text || null == title) {
            responser.catchErr(ctx, "参数缺失");
            return;
        }
       
        var user = await auth.user(ctx);

        if (user) {
            var post = await Post.create({
                text: text,
                UserId: user.id,
                title: title
            });
            responser.success(ctx, post);
        }
        else {
            responser.catchErr(ctx, "用户没登录")
        }
    });
    /**
     * 回帖,text是内容,type是类型,1是回复帖头,2是回复帖子,    uId是回复的帖子的id
     */
    router.get('/forum/addComment', async(ctx, next) => {
        let body = ctx.request.body
       
        var text = body.text;
        var uId = body.uId;
        var type = body.type;
        if (null == text || null == uId || null == type) {
            responser.catchErr(ctx, "params miss");
            return;
        }
        
        var user = await auth.user(ctx);
        // var user = true;//测试阶段

        if (user) {
            var reply = await Reply.create({
                text: text,
                type: type,
                UserId: user.id,
                PostId: uId
            });

            var post = await Post.findById(uId);
            post.readCount++;
            post.replyCount++;
            post.save();
            responser.success(ctx, reply);
        }
        else {
            responser.catchErr(ctx, "user has not logined");
        }
    })
};